package com.ghxxzx.daglcustom.business_form.web;

import com.ghxxzx.daglcustom.business_form.domain.dto.FormSubmitDto;
import com.ghxxzx.daglcustom.business_form.service.FormDuplicateService;
import com.ghxxzx.daglcustom.business_form.service.FormValsService;
import com.ghxxzx.daglcustom.business_form.service.ModelJsonService;
import com.alibaba.fastjson.JSONObject;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.tmsps.ne4spring.base.BaseAction;
import org.tmsps.ne4spring.utils.JsonUtil;
import org.tmsps.ne4spring.utils.wrapper.WrapMapper;
import org.tmsps.ne4spring.utils.wrapper.Wrapper;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Set;

@RestController
@RequestMapping("/form/workflow")
public class FormSubmitAction2 extends BaseAction {

	@Resource
	private TaskService taskService;
	@Autowired
	private FormValsService formValsService;
	@Autowired
	private FormDuplicateService formDuplicateService;
	@Autowired
	private ModelJsonService modelJsonService;

	// 保存草稿
	@PostMapping("/saveDoc")
	public Wrapper<String> saveDoc(@Valid @RequestBody FormSubmitDto formSubmitDto) {
		String form = formSubmitDto.getForm();

		logger.info("表单保存草稿...");
		JSONObject formJson = JsonUtil.jsonStrToJsonObject(form);
		logger.info("formJson--{}", formJson);
		// 保存表单以及表单的值
		formValsService.saveFormVals(formSubmitDto);

		logger.info("表单保存草稿成功!");
		return WrapMapper.ok("保存成功!");
	}

	@PostMapping("/submit")
	public Wrapper<String> submit(@Valid @RequestBody FormSubmitDto formSubmitDto) {
		String task_id = formSubmitDto.getTask_id();
		String form = formSubmitDto.getForm();

		Task task = taskService.createTaskQuery().taskId(task_id).singleResult();
		if (task == null) {
			return WrapMapper.ok("您已提交成功!");
		}

		logger.info("表单提交...");
		JSONObject formJson = JsonUtil.jsonStrToJsonObject(form);
		logger.info("formJson--{}", formJson);
		Set<String> keySet = formJson.keySet();
		for (String key : keySet) {
			Object val = formJson.getString(key);
			logger.info("{}:{}", key, val);
			taskService.setVariable(task.getId(), key, val);
			taskService.setVariableLocal(task.getId(), key, val);
		}
		// 保存表单以及表单的值
		formValsService.saveFormVals(formSubmitDto);

		logger.info("表单相关操作完成!");

		taskService.complete(task.getId());

		logger.info("检查重复审批人, 自动去重.");
		// formDuplicateService.doDuplicateTask(task.getProcessInstanceId());
		logger.info("根据完成时间,自动设置提醒方式.");
		modelJsonService.dueNextTaskPushHandle(task.getProcessInstanceId());

		return WrapMapper.ok("提交成功!");
	}

}
